package com.wxtwxt.ruralmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wxtwxt.ruralmall.common.utils.HttpUtils;
import com.wxtwxt.ruralmall.member.entity.MemberLevelEntity;
import com.wxtwxt.ruralmall.member.exception.EmailExistsException;
import com.wxtwxt.ruralmall.member.exception.UserNameExistsException;
import com.wxtwxt.ruralmall.member.service.MemberLevelService;
import com.wxtwxt.ruralmall.member.vo.UserLoginVo;
import com.wxtwxt.ruralmall.member.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxtwxt.ruralmall.common.utils.PageUtils;
import com.wxtwxt.ruralmall.common.utils.Query;

import com.wxtwxt.ruralmall.member.dao.MemberDao;
import com.wxtwxt.ruralmall.member.entity.MemberEntity;
import com.wxtwxt.ruralmall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterVo userRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        userNameIsExist(userRegisterVo.getUserName());
        emailIsExist(userRegisterVo.getEmail());
        MemberLevelEntity memberLevelEntity = memberLevelService.findDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        memberEntity.setUsername(userRegisterVo.getUserName());
        memberEntity.setNickname(userRegisterVo.getUserName());
        memberEntity.setEmail(userRegisterVo.getEmail());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(userRegisterVo.getPassword());
        memberEntity.setPassword(encode);
        this.save(memberEntity);
    }

    @Override
    public void userNameIsExist(String userName) throws UserNameExistsException{
        long result = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(result > 0) {
            throw new UserNameExistsException();
        }
    }

    @Override
    public void emailIsExist(String email) throws EmailExistsException{
        long result = this.count(new QueryWrapper<MemberEntity>().eq("email", email));
        if(result > 0) {
            throw new EmailExistsException();
        }

    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        String userAccount = userLoginVo.getUserAccount();
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", userAccount).or().eq("email", userAccount));
        if(entity != null) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(userLoginVo.getPassword(), entity.getPassword());
            if(matches) {
                return entity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity login(String json) throws Exception {
        JSONObject jsonObject = JSON.parseObject(json);
        Map<String, String> map = new HashMap<>();
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        map.put("access_token", accessToken);
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get",null, map);
        if(response.getStatusLine().getStatusCode() == 200) {
            String toString = EntityUtils.toString(response.getEntity());
            JSONObject parseObject = JSON.parseObject(toString);
            Integer id = (Integer) parseObject.get("id");
            MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("soical_uid", "gitee" + "_" + id));
            if(memberEntity != null) {
                memberEntity.setAccessToken(accessToken);
                memberEntity.setExpiresIn(expiresIn);
                this.updateById(memberEntity);
                return memberEntity;
            }else {
                MemberEntity entity = new MemberEntity();
                MemberLevelEntity level = memberLevelService.findDefaultLevel();
                entity.setLevelId(level.getId());
                entity.setNickname((String) parseObject.get("name"));
                entity.setAccessToken(accessToken);
                entity.setExpiresIn(expiresIn);
                entity.setSoicalUid("gitee" + "_" + id);
                this.save(entity);
                return entity;
            }
        }
        return null;
    }

}